import 'dart:io';
import 'package:base_flutter/base_flutter.dart';
import 'package:dio/dio.dart';
// import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:install_apk_plugin/install_apk_plugin.dart';
import 'package:ls_work/permission/permission_request.dart';
import 'package:ls_work/res/colors.dart';
import 'package:ls_work/res/dimens.dart';
import 'package:ls_work/res/styles.dart';
// import 'package:ls_work/update_app_utils/version_utils.dart';
import 'package:ls_work/util/image_utils.dart';
import 'package:ls_work/util/toast.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:path_provider/path_provider.dart';

import '../util/flat_button.dart';

class UpdateDialog extends StatefulWidget {
  final Map netMap;
  final bool force;
  UpdateDialog({Key? key,required this.netMap,this.force = false});
  @override
  _UpdateDialogState createState() => _UpdateDialogState();
}

class _UpdateDialogState extends State<UpdateDialog> {
  CancelToken _cancelToken = CancelToken();
  bool _isDownload = false;
  double _value = 0;
  var version = "";

  String get _appFileName => "work_v${version}.apk";

  @override
  void dispose() {
    if (!_cancelToken.isCancelled && _value != 1) {
      _cancelToken.cancel();
    }
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    version = widget.netMap!["version"];
    if(widget.force){
      setState(() {
        _isDownload = true;
      });
      _checkPermission()
          .then((hasPermission) {
        if (hasPermission) {
          _download();
        }
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    Color primaryColor = Colours.app_main; //Theme.of(context).primaryColor;
    var updateStr = widget.netMap!["changelog"] as String?;
    if(updateStr==null||updateStr.isEmpty){
      updateStr = '1.bug修复。\n\n2.提升用户体验。';
    }

    return WillPopScope(
      onWillPop: () async {
        /// 使用false禁止返回键返回，达到强制升级目的
        return !widget.force;
      },
      child: Scaffold(
          resizeToAvoidBottomInset: false,
          backgroundColor: Colors.transparent,
          body: Center(
            child: Container(
                decoration: BoxDecoration(
                  color: Theme.of(context).canvasColor,
                  borderRadius: BorderRadius.circular(8.0),
                ),
                width: 280.0,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[
                    Container(
                        height: 120.0,
                        width: 280.0,
                        decoration: BoxDecoration(
                          borderRadius: const BorderRadius.only(
                              topLeft: const Radius.circular(8.0),
                              topRight: const Radius.circular(8.0)),
                          image: DecorationImage(
                            image: ImageUtils.getAssetImage('update_head',
                                format: 'jpg'),
                            fit: BoxFit.cover,
                          ),
                        )),
                    const Padding(
                      padding: const EdgeInsets.only(
                          left: 15.0, right: 15.0, top: 16.0),
                      child: const Text('新版本更新', style: TextStyles.textDark16),
                    ),
                    Padding(
                      padding: const EdgeInsets.symmetric(
                          horizontal: 15.0, vertical: 10.0),
                      child: Text(updateStr),
                    ),
                    Padding(
                      padding: const EdgeInsets.only(
                          bottom: 15.0, left: 15.0, right: 15.0, top: 5.0),
                      child: _isDownload
                          ? LinearProgressIndicator(
                              backgroundColor: Colours.line,
                              valueColor:
                                  AlwaysStoppedAnimation<Color>(primaryColor),
                              value: _value,
                            )
                          : Row(
                              mainAxisAlignment: widget.force?MainAxisAlignment.center:MainAxisAlignment.spaceBetween,
                              children: <Widget>[
                                if(!widget.force)
                                Container(
                                  width: 110.0,
                                  height: 36.0,
                                  child: FlatsButton(
                                    onPressed: () {
                                      // NavigatorUtils.goBack(context);
                                      Navigator.pop(context);
                                    },
                                    color: Colors.white,
                                    shape: RoundedRectangleBorder(
                                        borderRadius:
                                            BorderRadius.circular(18.0),
                                        side: BorderSide(
                                          color: primaryColor,
                                          width: 0.8,
                                        )),
                                    child: Text(
                                      '残忍拒绝',
                                      style:
                                          TextStyle(fontSize: Dimens.font_sp16),
                                    ),
                                  ),
                                ),
                                Container(
                                  width: 110.0,
                                  height: 36.0,
                                  child: FlatsButton(
                                    onPressed: () {
                                      if (defaultTargetPlatform ==
                                          TargetPlatform.android) {
                                        // Navigator.pop(context);
                                        // InstallApkPlugin.jumpToAppStore();
                                        setState(() {
                                          _isDownload = true;
                                        });
                                        _checkPermission()
                                            .then((hasPermission) {
                                          if (hasPermission) {
                                            _download();
                                          }
                                        });
                                      } else {}
                                    },
                                    color: primaryColor,
                                    shape: RoundedRectangleBorder(
                                      borderRadius: BorderRadius.circular(18.0),
                                    ),
                                    child: Text(
                                      '立即更新',
                                      style:
                                          TextStyle(fontSize: Dimens.font_sp16,color: Colors.white),
                                    ),
                                  ),
                                )
                              ],
                            ),
                    )
                  ],
                )),
          )),
    );
  }

  Future<String> _getPhoneLocalPath() async {
    final directory = Theme.of(context).platform == TargetPlatform.android
        ? await getExternalStorageDirectory()
        : await getApplicationDocumentsDirectory();
    return directory?.path??"";
  }



  ///下载apk
  _download() async {

    try {
      var root = await _getPhoneLocalPath();
      String fileParent = "${root}${Platform.pathSeparator}downlo";
      var parent = Directory(fileParent);
      if(!parent.existsSync()){
        print("12313123");
        parent.createSync(recursive: true);
      }
      String path = (fileParent) + "/${_appFileName}";
      File file = File(path);
      // var hasFile = await file.exists();
      // if(hasFile){
      //   InstallApkPlugin.installApk(path);
      //   setState(() {
      //     _isDownload = false;
      //   });
      //   return;
      // }
      // await DirectoryUtil.getInstance();
      // DirectoryUtil.createStorageDirSync(category: 'apk');
      // String path = DirectoryUtil.getStoragePath(
      //     fileName: 'landsea', category: 'apk', format: 'apk');
      // File file = File(path);
      var url = widget.netMap["url"];
      debugPrint('🍎' + url);
      await Dio().download(
        url,
        file.path,
        cancelToken: _cancelToken,
        onReceiveProgress: (int count, int total) {
          if (total != -1) {
            _value = count / total;
            setState(() {});
            if (count == total) {
              Navigator.pop(context);
              // InstallApkPlugin.install(path);
              InstallApkPlugin.installApk(path);
            }
          }
        },
      );
    } catch (e) {
      Toast.show('下载失败!');
      print(e);
      setState(() {
        _isDownload = false;
      });
    }
  }

  var permissions = [

    Permission.storage,
  ];
  Future<bool> _checkPermission() async {
    if (Platform.isAndroid) {
      // PermissionStatus permission = await PermissionHandler()
      //     .checkPermissionStatus(PermissionGroup.storage);
      // if (permission != PermissionStatus.granted) {
      //   Map<PermissionGroup, PermissionStatus> permissions =
      //       await PermissionHandler()
      //           .requestPermissions([PermissionGroup.storage]);
      //   if (permissions[PermissionGroup.storage] == PermissionStatus.granted) {
      //     return true;
      //   }
      // } else {
      //   return true;
      // }
      bool isLack = await PermissionRequest.isLackPermissions(permissions);
      if(isLack){
        return true;
      }else{
        PermissionRequest.requestPermissions(permissions).then((value) {
          if(value[Permission.storage]==PermissionStatus.granted){
            return true;
          }else{
            return false;
          }
        });
      }
    } else {
      return true;
    }
    return false;
  }
}
